package com.smart.community.property.controller;

import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.property.entity.GasFee;
import com.smart.community.property.service.IGasFeeService;
import com.smart.community.property.dto.GasFeeGenerateDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 燃气费管理控制器
 * @author Wu.Liang
 * @since 2024-12-21
 */
@RestController
@RequestMapping("/property/gas-fees")
@Tag(name = "燃气费管理", description = "燃气费账单生成、表读数、安全检查等接口")
@Slf4j
public class GasFeeController {

    @Autowired
    private IGasFeeService gasFeeService;

    /**
     * 分页查询燃气费账单
     * @author Wu.Liang
     */
    @GetMapping
    @Operation(summary = "分页查询燃气费账单", description = "支持按社区、状态等条件查询")
    public Result<PageResult<GasFee>> getGasFeeList(
            @Parameter(description = "社区ID") @RequestParam(required = false) Long communityId,
            @Parameter(description = "缴费状态：0-未缴费，1-已缴费，2-逾期") @RequestParam(required = false) Integer paymentStatus,
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) throws Exception {
        log.info("分页查询燃气费账单，社区ID: {}, 缴费状态: {}, 当前页: {}, 每页大小: {}", 
                communityId, paymentStatus, current, size);
        PageResult<GasFee> result = gasFeeService.getGasFeePage(current, size, communityId, paymentStatus);
        return Result.success("查询成功", result);
    }

    /**
     * 获取燃气费详情
     * @author Wu.Liang
     */
    @GetMapping("/{billId}")
    @Operation(summary = "获取燃气费详情", description = "获取指定燃气费账单的详细信息")
    public Result<GasFee> getGasBillDetail(
            @Parameter(description = "账单ID") @PathVariable Long billId) throws Exception {
        log.info("获取燃气费详情，账单ID: {}", billId);
        GasFee bill = gasFeeService.getById(billId);
        if (bill != null) {
            return Result.success("查询成功", bill);
        } else {
            return Result.fail("账单不存在");
        }
    }

    /**
     * 更新燃气费信息
     * @author Wu.Liang
     */
    @PutMapping("/{billId}")
    @Operation(summary = "更新燃气费信息", description = "更新指定燃气费账单的信息")
    public Result<Boolean> updateGasBill(
            @Parameter(description = "账单ID") @PathVariable Long billId,
            @Parameter(description = "费用信息") @RequestBody @Valid GasFee bill) throws Exception {
        log.info("更新燃气费信息，账单ID: {}", billId);
        bill.setId(billId);
        boolean success = gasFeeService.updateById(bill);
        if (success) {
            return Result.success("更新成功", true);
        } else {
            return Result.fail("更新失败");
        }
    }

    /**
     * 燃气费缴费
     * @author Wu.Liang
     */
    @PostMapping("/{billId}/pay")
    @Operation(summary = "燃气费缴费", description = "为指定燃气费账单进行缴费操作")
    public Result<Boolean> payGasFee(
            @Parameter(description = "账单ID") @PathVariable Long billId,
            @Parameter(description = "支付金额") @RequestParam BigDecimal paymentAmount,
            @Parameter(description = "支付方式") @RequestParam Integer paymentMethod) throws Exception {
        log.info("燃气费缴费，账单ID: {}, 金额: {}, 支付方式: {}", billId, paymentAmount, paymentMethod);
        boolean success = gasFeeService.payGasFee(billId, paymentAmount, paymentMethod);
        if (success) {
            return Result.success("缴费成功", true);
        } else {
            return Result.fail("缴费失败");
        }
    }

    /**
     * 删除燃气费记录
     * @author Wu.Liang
     */
    @DeleteMapping("/{billId}")
    @Operation(summary = "删除燃气费记录", description = "删除指定的燃气费记录")
    public Result<Boolean> deleteGasBill(
            @Parameter(description = "账单ID") @PathVariable Long billId) throws Exception {
        log.info("删除燃气费记录，账单ID: {}", billId);
        boolean success = gasFeeService.removeById(billId);
        if (success) {
            return Result.success("删除成功", true);
        } else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 生成燃气费账单
     * @author Wu.Liang
     */
    @PostMapping("/generate")
    @Operation(summary = "生成燃气费账单", description = "根据表读数生成燃气费账单")
    public Result<Integer> generateGasFee(
            @Parameter(description = "生成参数") @RequestBody @Valid GasFeeGenerateDTO generateDTO) throws Exception {
        log.info("生成燃气费账单，社区ID: {}, 计费月份: {}, 燃气单价: {}", 
                generateDTO.getCommunityId(), generateDTO.getBillingMonth(), generateDTO.getUnitPrice());
        int count = gasFeeService.generateGasFee(
                generateDTO.getCommunityId(), 
                generateDTO.getBillingMonth(), 
                generateDTO.getUnitPrice());
        return Result.success("生成成功", count);
    }

    /**
     * 提交燃气表读数
     * @author Wu.Liang
     */
    @PostMapping("/meter-reading")
    @Operation(summary = "提交燃气表读数", description = "提交燃气表读数并自动计算费用")
    public Result<Boolean> submitMeterReading(
            @Parameter(description = "房户ID") @RequestParam Long householdId,
            @Parameter(description = "表读数") @RequestParam BigDecimal reading,
            @Parameter(description = "读数日期") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate readingDate) throws Exception {
        log.info("提交燃气表读数，房户ID: {}, 表读数: {}, 读数日期: {}", householdId, reading, readingDate);
        boolean success = gasFeeService.submitMeterReading(householdId, reading, readingDate);
        if (success) {
            return Result.success("表读数提交成功", true);
        } else {
            return Result.fail("表读数提交失败");
        }
    }

    /**
     * 发送燃气费催缴提醒
     * @author Wu.Liang
     */
    @PostMapping("/{billId}/remind")
    @Operation(summary = "发送燃气费催缴提醒", description = "向用户发送燃气费催缴提醒通知")
    public Result<Boolean> sendGasReminder(
            @Parameter(description = "账单ID") @PathVariable Long billId,
            @Parameter(description = "提醒方式：sms-短信，email-邮件，app-APP推送") @RequestParam String remindType) throws Exception {
        log.info("发送燃气费催缴提醒，账单ID: {}, 提醒方式: {}", billId, remindType);
        boolean success = gasFeeService.sendGasReminder(billId, remindType);
        if (success) {
            return Result.success("提醒发送成功", true);
        } else {
            return Result.fail("提醒发送失败");
        }
    }

    /**
     * 批量发送燃气费催缴提醒
     * @author Wu.Liang
     */
    @PostMapping("/batch-remind")
    @Operation(summary = "批量发送燃气费催缴提醒", description = "批量向逾期用户发送燃气费催缴提醒")
    public Result<Map<String, Integer>> batchSendGasReminder(
            @Parameter(description = "社区ID") @RequestParam Long communityId,
            @Parameter(description = "提醒方式：sms-短信，email-邮件，app-APP推送") @RequestParam String remindType) throws Exception {
        log.info("批量发送燃气费催缴提醒，社区ID: {}, 提醒方式: {}", communityId, remindType);
        Map<String, Integer> result = gasFeeService.batchSendGasReminder(communityId, remindType);
        return Result.success("批量提醒发送成功", result);
    }

    /**
     * 批量提交燃气表读数
     * @author Wu.Liang
     */
    @PostMapping("/batch-meter-reading")
    @Operation(summary = "批量提交燃气表读数", description = "批量提交多个房间的燃气表读数")
    public Result<Map<String, Integer>> batchSubmitMeterReading(
            @Parameter(description = "社区ID") @RequestParam Long communityId,
            @Parameter(description = "表读数数据") @RequestBody List<Map<String, Object>> meterReadings) throws Exception {
        log.info("批量提交燃气表读数，社区ID: {}, 数据条数: {}", communityId, meterReadings.size());
        Map<String, Integer> result = gasFeeService.batchSubmitMeterReading(communityId, meterReadings);
        return Result.success("批量提交成功", result);
    }

    /**
     * 燃气安全检查
     * @author Wu.Liang
     */
    @GetMapping("/safety-check")
    @Operation(summary = "燃气安全检查", description = "检查燃气使用异常和安全风险")
    public Result<Map<String, Object>> gasSafetyCheck(
            @Parameter(description = "社区ID") @RequestParam Long communityId) throws Exception {
        log.info("燃气安全检查，社区ID: {}", communityId);
        Map<String, Object> result = gasFeeService.gasSafetyCheck(communityId);
        return Result.success("安全检查完成", result);
    }

    /**
     * 获取燃气费统计信息
     * @author Wu.Liang
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取燃气费统计信息", description = "获取指定社区的燃气费收缴统计")
    public Result<Map<String, Object>> getGasFeeStatistics(
            @Parameter(description = "社区ID") @RequestParam Long communityId,
            @Parameter(description = "年份") @RequestParam(defaultValue = "#{T(java.time.LocalDate).now().getYear()}") Integer year) throws Exception {
        log.info("获取燃气费统计信息，社区ID: {}, 年份: {}", communityId, year);
        Map<String, Object> statistics = gasFeeService.getGasFeeStatistics(communityId, year);
        return Result.success("查询成功", statistics);
    }

    /**
     * 查询用户未缴费燃气费账单
     * @author Wu.Liang
     */
    @GetMapping("/user/{userId}/unpaid")
    @Operation(summary = "查询用户未缴费燃气费账单", description = "获取指定用户的所有未缴费燃气费账单")
    public Result<List<GasFee>> getUnpaidGasBillsByUserId(
            @Parameter(description = "用户ID") @PathVariable Long userId) throws Exception {
        log.info("查询用户未缴费燃气费账单，用户ID: {}", userId);
        List<GasFee> bills = gasFeeService.getUnpaidGasFeesByUserId(userId);
        return Result.success("查询成功", bills);
    }
} 